/******************************************************************************
 * The contents of this file are subject to the   JDI License  Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Initial Developer of the Original Code is 陈慧然. Portions created by 
 * 陈慧然 are Copyright 陈慧然.
 * All Rights Reserved.
 *
 *              Contact john_holen@163.com for licensing alternatives.
 *
 *****************************************************************************/

package org.peony.db.base;

import java.sql.Connection;

import org.peony.exceptions.DataBaseOperationException;
import org.peony.models.MDBConfig;
import org.peony.standard.db.SAJDBCConnectionProviderFactory;
import org.peony.standard.db.operation.SIJDBCDatabaseOperation;
import org.peony.standard.unvarying.db.TranscationType;
import org.peony.tools.StringUtil;

/**
 * 
 * 
 * @author 陈慧然
 * @version Id: DBAdapter.java, v 0.000 2008-6-15 下午11:07:22 陈慧然 Exp
 */
public class JDBCDBAdapter {
	
	private PeonyDataSource dataSource;
	private SIJDBCDatabaseOperation dbo;
	private String dataSourceName;
	private Connection conn;
	
	public JDBCDBAdapter(String dataSourceName) throws DataBaseOperationException {
		if(StringUtil.isEmpty(dataSourceName))
			throw new DataBaseOperationException();
		this.dataSourceName = dataSourceName;
		try{
			dataSource = MDBConfig.getDataSource(dataSourceName);
			dbo = DBOAbstractFactory.getFactory(dataSource.getDbmsType()).getDBO();
		}catch(Exception e){
			throw new DataBaseOperationException(e);
		}
	}

	public SIJDBCDatabaseOperation getDbo() throws DataBaseOperationException {
		if(conn == null)
			conn = getConnection();
		dbo.setConnection(conn);
		return dbo;
	}

	private Connection getConnection()
			throws DataBaseOperationException {
		try {
			String transactionType = MDBConfig.getTransactionType();
			if (transactionType.equals(TranscationType.JTA))
				throw new DataBaseOperationException();
			PeonyDataSource dataSource = MDBConfig
					.getDataSource(dataSourceName);
			String dataSourceTransactionType = dataSource
					.getDataSourceTransactionType();
			if (StringUtil.isEmpty(dataSourceTransactionType)
					|| !dataSourceTransactionType.equals(TranscationType.JDBC))
				throw new DataBaseOperationException();
			String className = dataSource.getDataSourceProviderClassName();
			if (StringUtil.isEmpty(className))
				throw new DataBaseOperationException();
			return SAJDBCConnectionProviderFactory
					.getConnectionProviderFactory(className)
					.getConnectionProvider().getConnection();
		} catch (Exception e) {
			throw new DataBaseOperationException(e);
		}
	}
}
